package com.fw.application.controller.scheduling;

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.common.IdXD;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 定时 服务
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class SchedulingService {


    @Autowired
    private ITbCityCodeService cityCodeService;
    @Autowired
    private ITbUserCityJoinService joinService;
    @Autowired
    private ITbUserService userService;
    @Autowired
    private ITbConutrySortService conutrySortService;
    @Autowired
    private ITbWechatFootService wechatFootService;
    @Autowired
    private ITbSysRuleService ruleService;
    @Autowired
    private IdXD idXD;

    private AtomicInteger numbers = new AtomicInteger(0);

    /**
     * 统计全国排行
     * <p>
     * 每两个小时执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ? ")
    public void countrySort() {
        log.info("统计全国排行定时任务启动了....");
        TbSysRule startAndEndTime = ruleService.getById(8);
        if (LocalDateTime.now().compareTo(startAndEndTime.getStartTime()) < 0)
            return;
        if (LocalDateTime.now().compareTo(startAndEndTime.getEndTime()) > 0) {
            return;
        }
        userService.list(Wrappers.<TbUser>lambdaQuery().ge(TbUser::getNowCityCount, 1).eq(TbUser::getIsState, 1)).parallelStream().forEach(map -> {
            TbConutrySort one = conutrySortService.getOne(Wrappers.<TbConutrySort>lambdaQuery().eq(TbConutrySort::getUserId, map.getId()));
            if (one == null) {
                one = new TbConutrySort();
                one.setId(idXD.nextId());
            }

            one.setCityName(cityCodeService.getById(joinService.getOne(Wrappers.<TbUserCityJoin>lambdaQuery().eq(TbUserCityJoin::getUserId, map.getId()).eq(TbUserCityJoin::getIsType,1)).getCityCode()).getCityName());
            one.setCountFool(map.getCountFool());
            one.setNickName(map.getNickName());
            one.setImgUrl(map.getImgUrl());
            one.setUserId(map.getId());
            one.setNowCountCity(map.getNowCityCount());
            TbWechatFoot tbWechatFoot = wechatFootService.list(Wrappers.<TbWechatFoot>lambdaQuery().eq(TbWechatFoot::getUserId, map.getId()).orderByAsc(TbWechatFoot::getCreateTime)).get(0);
            TbUserCityJoin tbUserCityJoin = joinService.list(Wrappers.<TbUserCityJoin>lambdaQuery().eq(TbUserCityJoin::getUserId, map.getId()).orderByDesc(TbUserCityJoin::getCreateTime)).get(0);
            //计算时差毫秒
            one.setCountTime(Duration.between(tbWechatFoot.getCreateTime(), tbUserCityJoin.getCreateTime()).toMillis());
            one.setCountDayTime(DateUtil.formatBetween(one.getCountTime(), BetweenFormatter.Level.MILLISECOND));
            conutrySortService.saveOrUpdate(one);
        });

        log.info("统计全国排行定时任务结束了....");
    }


    /**
     * 更新用户的全国排行
     * <p>
     * 每两个小时执行一次
     */
    @Scheduled(cron = "0 0 */2 * * ?")
    public void countrySortUser() {
        log.info("更新用户的全国排行定时任务启动了....");
        TbSysRule startAndEndTime = ruleService.getById(8);
        if (LocalDateTime.now().compareTo(startAndEndTime.getStartTime()) < 0)
            return;
        if (LocalDateTime.now().compareTo(startAndEndTime.getEndTime()) > 0) {
            return;
        }
        userService.list(Wrappers.<TbUser>lambdaQuery().ge(TbUser::getNowCityCount, 1)).stream()
                .forEach(item -> {
                    int i = conutrySortService.list(Wrappers.<TbConutrySort>lambdaQuery()
                            .orderByDesc(TbConutrySort::getCountFool)
                            .orderByAsc(TbConutrySort::getCountTime))
                            .stream().map(map -> map.getUserId())
                            .collect(Collectors.toList())
                            .indexOf(item.getId());
                    if (i > 0)
                        item.setCountrySort(i).updateById();
                });


        log.info("更新用户的全国排行定时任务结束了....");
    }


    //todo 检测用户当日步数 零点清零

    @Scheduled(cron = "59 59 23 1/1 * ?")
    public void cleanUserDayFool() {
        log.info("检测用户当日步数 零点清零");
        TbSysRule startAndEndTime = ruleService.getById(8);
        if (LocalDateTime.now().compareTo(startAndEndTime.getStartTime()) < 0)
            return;
        if (LocalDateTime.now().compareTo(startAndEndTime.getEndTime()) > 0) {
            return;
        }
        userService.list().parallelStream().forEach(item -> {
            userService.updateById(item.setWechatFool(0));
        });
        log.info("检测用户当日步数 零点清零结束");
    }


}
